{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "b8674439",
   "metadata": {},
   "source": [
    "# Steady State Transport\n",
    "\n",
    "Simulating transport such as diffusion or flow is a key output of PNM.  This notebook will explain the underlying process for these simulations in OpenPNM.  \n",
    "\n",
    "The transport of a species between pore `i` and `j` is dictated by the conductance `g` of the conduit between these pores.  `g` depends on the geometry as well as the fluid properties. Consider the case of diffusion which is described by Fick's law:\n",
    "\n",
    "$$ n_A = D_{AB}\\frac{A}{L} \\Delta C_A = g^D \\Delta C_A $$\n",
    "\n",
    "$g^D$ is the diffusive conductance and is a function of pore diameter, shape, length, as well as the physical properties of the fluid such as composition, temperature, pressure, and so on. Determination of $g^D$ is the subject of a different notebook, so for the present purposes random values between 0 and 1.0 will be used.  Consider at 2x2 network:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "d604aeca",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openpnm as op\n",
    "import numpy as np\n",
    "op.visualization.set_mpl_style()\n",
    "\n",
    "pn = op.network.Cubic(shape=[2, 2, 1])\n",
    "air = op.phase.Phase(network=pn)\n",
    "air['throat.diffusive_conductance'] = np.random.rand(pn.Nt)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "16346729",
   "metadata": {},
   "source": [
    "## Creating the Coefficient Matrix\n",
    "\n",
    "The rate equation given above applies to each throat in the network. In a pore network we want to solve for the quantity of interest in each pore. Each pore in the network has many throats.  Depending on the concentrations in the neighboring pores the rate of diffusion through each throat may either be into or away from a given pore.  At steady state and in the absence of reaction, the net rate into pore `i` will be zero. Thus we can write the mass balance equation for pore `i` using summation notation as:\n",
    "\n",
    "$$ \\Sigma g_{i, j} (x_j - x_i) = 0 $$\n",
    "\n",
    "We can write the above equation for each pore in the network and obtain a system of coupled linear equations such that:\n",
    "\n",
    "$$ x = A^{-1} b $$\n",
    "\n",
    "where `b` is the right hand side of the balance equation. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "78f456d1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[-1.13706265  0.39776399  0.73929866  0.        ]\n",
      " [ 0.39776399 -1.36417473  0.          0.96641074]\n",
      " [ 0.73929866  0.         -1.43682166  0.697523  ]\n",
      " [ 0.          0.96641074  0.697523   -1.66393375]]\n"
     ]
    }
   ],
   "source": [
    "import scipy.sparse.csgraph as csg\n",
    "am = pn.create_adjacency_matrix(weights=-air['throat.diffusive_conductance'], fmt='csr', triu=False)\n",
    "A = csg.laplacian(am).todense()\n",
    "print(A)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "117261ce",
   "metadata": {},
   "source": [
    "## Applying Value and Rate Boundary Conditions\n",
    "\n",
    "If `b=0` for all pores then `x=0` throughout the network. We must apply boundary conditions to obtain a non-trivial result. One option is to apply \"rate\" boundary conditions, such that the net movement of the species in or out of a pore is not zero, such that: \n",
    "\n",
    "$$ \\Sigma g_{i, j} (x_j - x_i) = r_i $$\n",
    "\n",
    "Another option is to specify the value of the species of interest in a pore. In this case the balance equation can be replaced with:\n",
    "\n",
    "$$ x_i = b_i $$\n",
    "\n",
    "Let's set $x_0 = 2.0$ and $r_3 = -0.5$.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "9f506711",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The A matrix is:\n",
      " [[ 1.          0.          0.          0.        ]\n",
      " [ 0.39776399 -1.36417473  0.          0.96641074]\n",
      " [ 0.73929866  0.         -1.43682166  0.697523  ]\n",
      " [ 0.          0.96641074  0.697523   -1.66393375]]\n",
      "The b matrix is:\n",
      " [2.  0.  0.  0.5]\n"
     ]
    }
   ],
   "source": [
    "b = np.zeros([pn.Np, ], dtype=float)\n",
    "b[0] = 2.0\n",
    "A[0, :] = 0.0\n",
    "A[0, 0] = 1.0\n",
    "b[3] = 0.5\n",
    "print(\"The A matrix is:\\n\", A)\n",
    "print(\"The b matrix is:\\n\", b)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1ba7e343",
   "metadata": {},
   "source": [
    "## Solving the System of Equations\n",
    "\n",
    "One the coefficient matrix has been built from the system of equation, and boundary conditions are applied, we can solve the system $x = A^{-1}b$ to find $x_i$ in each pore.  This can be done using any number of numerical solvers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "2055702a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2.         1.44713857 1.62113873 1.21958691]\n"
     ]
    }
   ],
   "source": [
    "from scipy.linalg import solve\n",
    "x = solve(A, b)\n",
    "print(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1d2e562e",
   "metadata": {},
   "source": [
    "## Sparse Matrices\n",
    "\n",
    "In the above example the `A` matrix was small so we could convert it to dense form. In a real network the coefficient matrix will be much larger so requires dense representation. The above process is the same, but some of the numerical steps are different to account for the sparse nature of the coefficient matrix. In particular the application of value BCs is more complicated:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3abc4552",
   "metadata": {},
   "outputs": [],
   "source": [
    "import scipy.sparse.csgraph as csg\n",
    "am = pn.create_adjacency_matrix(weights=-air['throat.diffusive_conductance'], fmt='coo', triu=False)\n",
    "A = csg.laplacian(am)\n",
    "b = np.zeros([pn.Np, ], dtype=float)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e0d0c3e1",
   "metadata": {},
   "source": [
    "We can set the rate boundary condition in pore 3 in the same manner:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "07cbf18c",
   "metadata": {},
   "outputs": [],
   "source": [
    "b[3] = 0.5"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ab742d53",
   "metadata": {},
   "source": [
    "Setting the value BC on pore 0 requires setting all elements in row 0 to 0, except the diagonal.  However, in sparse form this cannot be done with direct indexing.  Instead, we can inspect the `row` attribute of `A` to find entries on row 0:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "id": "455a5348",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2 1 1 3 2 3 0 1 2 3]\n"
     ]
    }
   ],
   "source": [
    "print(A.row)\n",
    "hits = A.row == 0"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6a645561",
   "metadata": {},
   "source": [
    "Now we set the `data` values to zero at these locations:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "id": "8582456d",
   "metadata": {},
   "outputs": [],
   "source": [
    "A.data[hits] = 0.0"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cd2067d7",
   "metadata": {},
   "source": [
    "Then add a 1.0 in the diagonal:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "id": "3ec6eebf",
   "metadata": {},
   "outputs": [],
   "source": [
    "diag = A.diagonal()\n",
    "diag[0] = 1.0\n",
    "A.setdiag(diag)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "84788a3d",
   "metadata": {},
   "source": [
    "And finally we can use `eliminate_zeros` to convert it into a proper sparse representation again:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "id": "0f5f86fd",
   "metadata": {},
   "outputs": [],
   "source": [
    "A.eliminate_zeros()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5e8527ab",
   "metadata": {},
   "source": [
    "And let's not forget to add the value BC to `b`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "id": "1ec371a3",
   "metadata": {},
   "outputs": [],
   "source": [
    "b[0] = 2.0"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dc500c4a",
   "metadata": {},
   "source": [
    "Let's inspect our new coefficient matrix to be sure:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "id": "79d6afb2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The A matrix is:\n",
      " [[ 1.          0.          0.          0.        ]\n",
      " [ 0.39776399 -1.36417473  0.          0.96641074]\n",
      " [ 0.73929866  0.         -1.43682166  0.697523  ]\n",
      " [ 0.          0.96641074  0.697523   -1.66393375]]\n",
      "The b matrix is:\n",
      " [2.  0.  0.  0.5]\n"
     ]
    }
   ],
   "source": [
    "print(\"The A matrix is:\\n\", A.todense())\n",
    "print(\"The b matrix is:\\n\", b)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "352b30b9",
   "metadata": {},
   "source": [
    "Now we are ready to use the sparse solvers in `scipy`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "id": "639d0dd8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2.         1.44713857 1.62113873 1.21958691]\n"
     ]
    }
   ],
   "source": [
    "from scipy.sparse.linalg import spsolve\n",
    "x = spsolve(A.tocsr(), b)\n",
    "print(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "72df7a0a",
   "metadata": {},
   "source": [
    "We can see the numerical results are idential.  The additional effort required to deal with the sparse format is worth it since large network would become numerically intractable very quickly."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
